package com.wiken.storeservice.service.impl;

import com.wiken.servicecommon.common.Code;
import com.wiken.servicecommon.common.R;
import com.wiken.servicecommon.common.TokenUtil;
import com.wiken.servicecommon.common.exception.DefaultException;
import com.wiken.storeservice.entity.Type;
import com.wiken.storeservice.feign.UserServiceFeignClient;
import com.wiken.storeservice.mapper.TypeMapper;
import com.wiken.storeservice.service.ITypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wiken
 * @since 2022-12-28
 */


@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type> implements ITypeService {

    @Autowired
    UserServiceFeignClient userServiceFeignClient;
    boolean hasAdministrator(String token){
        Claims claims = TokenUtil.parseToken(token);

        String userId = claims.get("userId", String.class);

        boolean result = userServiceFeignClient.getAdministratorById(userId);

        return result;
    }
    @Override
    public boolean addType(Type type, String token) {

        if(!hasAdministrator(token)) throw new DefaultException(Code.ERROR_AUTHORIZATION, "添加类型失败");

        int success = baseMapper.insert(type);
        return success > 0;
    }

    @Override
    public boolean updateType(Type type, String token) {
        if(!hasAdministrator(token)) throw new DefaultException(Code.ERROR_AUTHORIZATION, "修改类型失败");

        int success = baseMapper.updateById(type);
        return success > 0;
    }

    @Override
    public boolean deleteType(Type type, String token) {
        if(!hasAdministrator(token)) throw new DefaultException(Code.ERROR_AUTHORIZATION, "删除类型失败");

        int success = baseMapper.deleteById(type);

        return success > 0;
    }

    @Override
    public List<Type> getTypes() {
        List<Type> types = baseMapper.selectList(null);
        return types;
    }
}
